const system = require('./../system')
const dao = require('./../dao')
const netRequest = require('./../netRequest')
const config = require('./../../config')
const {session} = require('electron')
const path = require('path')
const fs = require('fs');


let exec_status = false;

function request(type,url,data,headers,resultData,callback){
    if(exec_status){
        throw new Error("正在执行中，请勿操作..");
    }else{
        exec_status = true;
    }
    if(type == 0 || type == 2){
        data.comment_id = '';
        data['info_type'] = 0;
        data['load_history'] = 0;
        data['load_order'] = 0;
        requestComment(type,url,data,headers,resultData,callback);
    }else {
        requestRank(url,data,1,headers,resultData,callback)
    }
}

async function requestComment(type,url,data,headers,resultData,callback) {
    console.log(url,data,resultData.length)
    // headers = {
    //     'authority': 'appgpgezlza6405.h5.xiaoeknow.com',
    //         'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7',
    //         'alive_id': 'l_65b46771e4b04c10a127e1ab',
    //         'cache-control': 'no-cache',
    //         'call_referer': 'h5',
    //         'cookie': 'shop_version_type=4; dataUpJssdkCookie={"wxver":"","net":"","sid":""}; sensorsdata2015jssdkcross=%7B%22%24device_id%22%3A%2218d5ec507ed1d9-0f2345ed3d1c5a-1f525637-1296000-18d5ec507ee8a8%22%7D; ko_token=041d0b84cf429019e4076517cca853b8; sa_jssdk_2015_appgpgezlza6405_h5_xiaoeknow_com=%7B%22distinct_id%22%3A%22u_65b75ed17b97b_ygqPzsLrpZ%22%2C%22first_id%22%3A%2218d5449ef418db-03fc8d1485b862-1f525637-1296000-18d5449ef42e08%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%7D; logintime=1707106136',
    //         'origin': 'https://appgpgezlza6405.h5.xiaoeknow.com',
    //         'pragma': 'no-cache',
    //         'referer': 'https://appgpgezlza6405.h5.xiaoeknow.com/v2/course/alive/l_65b46771e4b04c10a127e1ab?type=2&resource_type=4&resource_id=l_65b46771e4b04c10a127e1ab&app_id=appGPgezLzA6405&share_user_id=u_5e91ad6170eae_HhxY7mA3bw&share_type=5&scene=%E9%82%80%E8%AF%B7%E9%93%BE%E6%8E%A5&pro_id=p_65139bfbe4b064a863ba1442&sw=1&share_scene=1',
    //         'sec-ch-ua': '"Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"',
    //         'sec-ch-ua-mobile': '?0',
    //         'sec-ch-ua-platform': '"macOS"',
    //         'sec-fetch-dest': 'empty',
    //         'sec-fetch-mode': 'cors',
    //         'sec-fetch-site': 'same-origin',
    //         'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
    // }
    try{
        ///休息100到300毫秒
        let sleep_seconds = system.getRandomInt(1, 3) * 100;
        await system.sleep(sleep_seconds);
        netRequest.request({url: url, method: 'post', headers: headers, data: data}).then(function(r){
            if(r.status == 200){
                let result = r.data;
                if (result && result.code == 0) {
                    let msgs = result.data.msgs;
                    let comment_id = null;
                    for (let i = 0; i < msgs.length; i++) {
                        let msg_data = msgs[i];
                        let comment_data = {uid:msg_data.user_id,nickname:msg_data.wx_nickname,content:msg_data.org_msg_content,create_time:msg_data.created_timestamp};
                        resultData.push(comment_data);
                    }
                    let finish = result.data.finish;
                    if(finish){
                        callback(resultData);
                        exec_status = false;
                    }else{
                        if(type == 0){
                            comment_id = msgs[msgs.length-1].comment_id;
                        }else{
                            comment_id = msgs[0].comment_id;
                        }
                        data['comment_id'] = comment_id;
                        data['info_type'] = type;
                        data['load_history'] = 0;
                        data['load_order'] = 1;
                        data['size'] = 50;
                        requestComment(type,url,data,headers,resultData,callback);
                    }
                }else{
                    console.log('no data',r);
                    callback(resultData);
                    exec_status = false;
                }
            }
        }).catch(function(e){
            console.log(e);
            if(e.code == 'ECONNRESET'){
                requestComment(type,url,data,headers,resultData,callback);
            }else{
                exec_status = false;
            }
        });

    }catch (e) {
        console.log(e);
        exec_status = false;
    }finally {
    }
    return true;
}

async function requestRank(url,data,page,headers,resultData,callback) {
    console.log(url,data)

    try{
        //休息100到300毫秒
        let sleep_seconds = system.getRandomInt(1, 3) * 100;
        await system.sleep(sleep_seconds);
        netRequest.request({url: url, method: 'post', headers: headers, data: data}).then(function(r){
            if(r.status == 200) {
                let result = r.data;
                if (result && result.code == 0) {
                    let msgs = result.data.rank_list;
                    for (let i = 0; i < msgs.length; i++) {
                        let msg_data = msgs[i];
                        let comment_data = {
                            uid: msg_data.user_id,
                            nickname: msg_data.wx_nickname,
                            rank: msg_data.rank,
                            time: parseFloat((msg_data.time / 60).toFixed(2))
                        };
                        resultData.push(comment_data);
                    }
                    let finish = result.data.is_finish;
                    if (finish || resultData.length == 1000) {
                        callback(resultData);
                        exec_status = false;
                    } else {
                        page++;
                        data.bizData['page'] = page;
                        // data.bizData['page_size'] = 100;
                        requestRank(url, data, page, headers, resultData, callback);
                    }
                } else {
                    console.log('no data', r);
                    callback(resultData);
                    exec_status = false;
                }
            }
        }).catch(function(e){
            console.log(e);
            if(e.code == 'ECONNRESET'){
                requestRank(url,data,page,headers,resultData,callback);
            }else{
                exec_status = false;
            }
        });

    }catch (e) {
        console.log(e);
        exec_status = false;
    }finally {
    }
    return true;
}
function getApplicationData(){
    let filePath = config.local_store_file_path
    let localData = fs.readFileSync(filePath, 'utf8');

    filePath = config.session_store_file_path;
    let sessionData = fs.readFileSync(filePath, 'utf8');

    filePath = config.cookie_store_file_path;
    let cookieData = fs.readFileSync(filePath, 'utf8');
    return {localData:localData,sessionData:sessionData,cookieData:cookieData}

}



module.exports = {
    request,

};
